<script>

var WaveCheck = {
  inboxURL: 'https://wave.google.com/wave/?nouacheck',
  pollTimeout: 120000,
  timeout: 30000,
  timerId: -1,
  checkInbox: function() {
    var xhr = new XMLHttpRequest();
    try {
      console.log("request..");
      xhr.onload = function() {
        console.log("readystate: " + xhr.readyState);
        if (WaveCheck.timerId != -1) window.clearTimeout(WaveCheck.timerId);
        if (xhr.responseText) {
          /* Ok, we got our feeds */
          console.log("response..");
          var data = xhr.responseText.match(/var json = (\{"r":"\^d1".*\});/);
          if(!data){
            /* Wrong page, report login error */
            WaveCheck.update('E-LO');
            return;
          }
          //console.log(data[1]);
          var json;
          try {
            json = JSON.parse(data[1]);
          } catch(e) {
            console.log('Parse error: ' + e);
          }
          if (!json) {
            /* Illegal response */
            WaveCheck.update('E-JS');
            return;
          }
          var inbox=json.p[1];
          var messages=[];
          var unread=0;
          for (var n in inbox) {
            console.log('Checking message ' + n);
            if (parseInt(inbox[n][7]) /* unread */) {
              console.log('Found unread: ' + inbox[n][9][1]);
              messages.push(inbox[n][9][1]);
              unread++;
            }
          }
          /* Report unread */
          WaveCheck.update(unread);
        } else {
          /* Must be a login error */
          console.log('Please login!');
          WaveCheck.update('E-LO');
        }

        WaveCheck.schedule();
      }
      
      xhr.onerror = function(error) {
        console.log('error: ' + error
          +', readyState: ' + this.readyState
          + ', statusCode: ' + this.status);
      }

      xhr.open("GET", this.inboxURL, true);
      xhr.send(null);

      // Give up after 5 seconds
      this.timerId = window.setTimeout(function() {
        console.log("Gave up...");
        WaveCheck.update('E-TO');
        xhr.abort();
        /* Try again later... */
        WaveCheck.schedule();
      }, WaveCheck.timeout);
    } catch(e) {
      console.log("ex: " + e);
      console.error("exception: " + e);
      this.schedule();
    }
  },
  update: function (count) {
    if (typeof(count) == 'number') {
      count = count.toString();
    }
    chrome.browserAction.setBadgeText({ text: count });
  },
  schedule: function() {
    window.setTimeout(function(thisObj) {thisObj.checkInbox()}, this.pollTimeout, this);
  }
};

chrome.browserAction.onClicked.addListener(function(tab) {
  // check if there is a tab opened
  var regEx = /^https:\/\/wave\.google\.com/;
  chrome.tabs.getAllInWindow(null, function(tabs){
    var tabId = null;
    for (var i in tabs) {
      if (regEx.test(tabs[i].url)) {
        console.log('found: ' + [tabs[i].url, tabs[i].id].join(', '));
        tabId = tabs[i].id;
        break;
      }
    }
    if (tabId) {
      chrome.tabs.update(tabId, { selected: true });
    } else {
      chrome.tabs.create({
          url: 'https://wave.google.com/wave/'
      });
    }
  });
});
WaveCheck.checkInbox();
</script>
